
package com.mephi.controller.action;


import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import org.apache.log4j.Logger;
import com.mephi.MephistoChess;
import com.mephi.gui.GUI;
import com.mephi.interfaces.Game;
import com.mephi.interfaces.LoadSaveGame;
import com.mephi.interfaces.Profile;
import com.mephi.io.LoadSaveGameImpl;
import com.mephi.model.Move;
import com.mephi.model.profile.ProfileMapSingleton;
import com.mephi.util.Ext;
import com.mephi.util.filter.FileFilter;


/**
 * Simple implementation of loading game action in another thread.
 * @author mephisto
 * 2011-05-28
 * 1.0
 */
public class LoadGameAction implements Runnable
{
	public LoadGameAction(Profile profile)
	{
		this.profile = profile;
	}

	@Override
	public void run()
	{
		JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        List<String> extensionList =  new ArrayList<String>();
        extensionList.add(Ext.xml.toString());
        chooser.setFileFilter(new FileFilter(extensionList));
        int r = chooser.showOpenDialog(MephistoChess.gui.getFraMainFrame());
        if (r != JFileChooser.APPROVE_OPTION) return;
        logger.info("Selected file: " + chooser.getSelectedFile().getAbsolutePath());

        LoadSaveGame<Move> loader = new LoadSaveGameImpl();

        String filename =  chooser.getSelectedFile().getAbsolutePath();
        Game<Move> game = loader.loadGame(filename);       
        logger.info("Selected file: " + filename);
        
        profile.getGameMap().put("1", game);
		ProfileMapSingleton.INSTANCE.getProfiles().put(profile.getName(), profile);
		//repainting game score result
		GUI.INSTANCE.repaintMovesPanel();
		GUI.INSTANCE.setStartingPosition();
		
		logger.info("Loading has been finished");
	}
	
	
	private Logger logger = Logger.getLogger("LOG");
	private Profile profile;
}
